class Image < ActiveRecord::Base
  belongs_to :category
  attr_accessor :large_image
  attr_accessor :thumbnail
  
  validates_presence_of :category_id,:name
  #before_validation_on_create :validate_create

  def validate_on_create
    #Checking for conflict filename
    errors.add(:large_image, " exist. Please rename it and try upload again.") if  conflict_filename("public#{generate_path(self.large_image,self.category_id,'full')}")
    errors.add(:thumbnail, " exist. Please rename it and try upload again.") if conflict_filename("public#{generate_path(self.thumbnail,self.category_id,'thumb')}")
    errors.add(:large_image,'can\'t be empty' )if conflict_dir("public#{generate_path(self.large_image,self.category_id,'full')}")
    errors.add(:thumbnail,'can\'t be empty')if conflict_dir("public#{generate_path(self.thumbnail,self.category_id,'thumb')}")
    errors.add(:large_image,'must be a GIF, JPG, or PNG image')if sanitize_filename(self.large_image.original_filename)!~%r{\.(gif|jpg|png|GIF|JPG|PNG)$}i
    errors.add(:thumbnail,'must be a GIF, JPG, or PNG image')if sanitize_filename(self.thumbnail.original_filename)!~%r{\.(gif|jpg|png|GIF|JPG|PNG)$}i
  end
  
  def validate_on_update
    if self.large_image.inspect !~ %r{.+StringIO*.}i
      errors.add(:large_image,'must be a GIF, JPG, or PNG image')if (sanitize_filename(self.large_image.original_filename)!~%r{\.(gif|jpg|png|GIF|JPG|PNG)$}i)&&(!self.large_image.original_filename.empty?)
    end
    if self.thumbnail.inspect !~ %r{.+StringIO*.}i
      #raise self.large_image.original_filename
      errors.add(:thumbnail,"must be a GIF, JPG, or PNG image#{self.thumbnail.original_filename}")if (sanitize_filename(self.thumbnail.original_filename)!~%r{\.(gif|jpg|png|GIF|JPG|PNG)$}i)&&(!self.thumbnail.original_filename.empty?)
    end
  end
  
  after_destroy :delete_files
    
  GALLERY_IMAGES_PATH = '/images/gallery'
  ########################### PUBLIC ###############################################
  def create_files
    save_file("public#{self.image_url}",self.large_image)    
    save_file("public#{self.thumb_url}",self.thumbnail)    
  end
  
  def update_file(type)
    save_file("public#{self.image_url}",self.large_image) if type=='full'
    save_file("public#{self.thumb_url}",self.thumbnail) if type=='thumb'
  end
  
  def define_urls(path='')
    if path==''
      self.image_url=generate_path(self.large_image,self.category_id,'full')
      self.thumb_url=generate_path(self.thumbnail,self.category_id,'thumb')    
    elsif path=='full'
      self.image_url=generate_path(self.large_image,self.category_id,path)
      self.save
    elsif path=='thumb'
      self.thumb_url=generate_path(self.thumbnail,self.category_id,path)    
      self.save
    end
  end
  
  def delete_files(type='')
    if type==''
    File.delete("public/#{self.image_url}") if File.exists?("public/#{self.image_url}")
    File.delete("public/#{self.thumb_url}") if File.exists?("public/#{self.thumb_url}")
    elsif type=='full'      
      File.delete("public#{self.image_url}") if File.exists?("public#{self.image_url}")
    elsif type=='thumb'
      File.delete("public#{self.thumb_url}") if File.exists?("public#{self.thumb_url}")
    end
  end
  
  private
  ############################### PRIVATE ########################################
  def generate_path(file_name,category,type)
    file_name=sanitize_filename(file_name.original_filename)    
    "#{GALLERY_IMAGES_PATH}/#{type}/#{category}/#{file_name}"
  end
  
  def conflict_filename(path)
    File.file?(path) if File.exist?(path)    
  end
  
  def conflict_dir(path)
    File.directory?(path) if File.exist?(path)    
  end    
  
  def sanitize_filename(file_name)
    # get only the filename, not the whole path (from IE)
    just_filename = File.basename(file_name) 
    # replace all none alphanumeric, underscore or perioids with underscore
    just_filename.gsub(/[^\w\.\_]/,'_') 
  end
  
  def save_file(path_to_file,data)
    if !File.exists?(File.dirname(path_to_file))
      Dir.mkdir(File.dirname(path_to_file))
    end
    File.open(path_to_file, "wb") { |f| f.write(data.read) }    
  end  
end